package com.mutual.assistance.auth.aop;

import com.mutual.assistance.exception.BizException;
import com.mutual.assistance.response.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * @author chenyuxin
 * @version 1.0
 * @description oauth2统一认证返回
 * @date 2023/4/28 15:05
 */
@Slf4j
@Component
@Aspect
public class AuthTokenAspect {

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        try {
            Object proceed = pjp.proceed();

            if (proceed == null) {
                return new ResponseEntity<>(R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), R.Execute_to_obtain_an_empty_object), HttpStatus.INTERNAL_SERVER_ERROR);
            }

            ResponseEntity responseEntity = (ResponseEntity) proceed;
            OAuth2AccessToken body = (OAuth2AccessToken) responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                assert body != null;
                String token = body.getValue();
                log.error("获取到token：{}", token);
                return new ResponseEntity<>(R.success(body, R.LOGIN_WAS_SUCCESSFUL), HttpStatus.OK);
            }

            log.error("error:{}", responseEntity.getStatusCode());
            return new ResponseEntity<>(R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), R.UNKNOWN_ERROR), HttpStatus.OK);

        } catch (Exception e) {
            BizException ex = null;
            try {
                ex = (BizException) e;
            } catch (Exception exc) {
                return new ResponseEntity<>(R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()), HttpStatus.OK);
            }
            return new ResponseEntity<>(R.fail(ex.getCode(), ex.getMessage()), HttpStatus.OK);
        }
    }

}


